package com.nhncorp.pleiades.master;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SplitBrainTimer {
  
  private Map<String, Long> timeMap;
  private long timeout;
  
  public SplitBrainTimer(long time) {
    timeMap = new ConcurrentHashMap<String, Long>();
    timeMap.put("start", new Long(0));
    timeMap.put("stop", new Long(0));
    this.timeout = time;
  }
  
  public long stayTime() {
    synchronized(timeMap) {
      long start = timeMap.get("start");
      long end = timeMap.get("stop");
      long now = System.currentTimeMillis();
      if(end > start) {
        if( (now-start) > timeout ) {
          return 0L;
        }
        return (end - start);  
      }
      return (System.nanoTime() - start);
    }
  }
  
  public long lastTime() {
    synchronized(timeMap) {
      return timeMap.get("start");
    }
  }
  
  public void start() {
    timeMap.put("start", new Long(System.currentTimeMillis()));
  }
  
  public void stop() {
    timeMap.put("stop", new Long(System.currentTimeMillis()));
  }
}
